package com.example.androidapp2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import java.util.Locale;
import com.example.androidapp2.DbClasses.ItemCategoria;
import com.example.androidapp2.DbClasses.ItemIngresos;
import com.example.androidapp2.DbClasses.Utils;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.xyzdesa.droidnomy.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView.ScaleType;

public class MainActivity extends Activity {	
	DbAdapter DbConect;
	private AdView adView;

	public PopUpModifica pupModif;
	private PopUpCategorias pupCate;
	private PopUpPorcentajes pupPorce;
	public PopUpConfirma pupConfirma;
	private PopUpConfig pupConfig;
	public PopUpTarjeta pupTarjeta;
	public PopUpAyuda pupAyuda;
	public PopUpRating pupRating;
	//private Pop

	//PantallaPrincipal	
	private Button btnResta;
	private EditText txtIngresos;
	private EditText txtEgresos;
	private EditText txtResta;		
	private TextView lblPorcentaje;	
	private TextView lblErrores;
	private ProgressBar skTotal;
	private Spinner spnCategorias;
	private CheckBox chbMedio;	

	private Button btnMil;
	private Button btnQuinientos;
	private Button btnCien;
	private Button btnCincuenta;
	private Button btnDiez;
	private Button btnCinco;
	private Button btnUno;
	private ImageButton btnAtras;
	private ImageButton btnDeshacer;
	private ImageButton btnAyuda;

	private ImageButton btnIr;
	private ImageButton btnVolver;
	private ViewFlipper flpView;
	private TableLayout tblIngresos;

	private ImageButton btnCategorias;	
	private String AdUnitId="a1502ab8f63427a";
	private List<Integer> ValoresAnteriores;
	private List<Integer> IdsGrilla;
	private List<ItemIngresos> PagosGrilla;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try{
			super.onCreate(savedInstanceState);
			setContentView(R.layout.view_flipper);
			if(DBOpen()){						
				Utils.Ctx = this;

				int l = DbConect.GetTotalLaunches();
				DbConect.SetTotalLaunches();
				adView = new AdView(this, AdSize.BANNER, AdUnitId);
				LinearLayout lyt = (LinearLayout) findViewById(R.id.lytAds);
				lyt.addView(adView);

				AdRequest adRequest = new AdRequest();
				adRequest.addTestDevice(AdRequest.TEST_EMULATOR);			
				adView.loadAd(adRequest);			

				pupModif = new PopUpModifica(this, DbConect);
				pupCate = new PopUpCategorias(this, DbConect);
				pupPorce = new PopUpPorcentajes(this, DbConect, this);
				pupConfirma = new PopUpConfirma(this, DbConect,pupModif);
				pupConfig = new PopUpConfig(this, DbConect);
				pupTarjeta = new PopUpTarjeta(this, DbConect);
				pupAyuda =  new PopUpAyuda(this);
				pupRating = new PopUpRating(this, DbConect);

				IdsGrilla = new ArrayList<Integer>();
				PagosGrilla = new ArrayList<ItemIngresos>();

				SetControls();
				SetControlValues();
				if( DbConect.SetUltimoIngreso())
					pupModif.show(false);

				if(!DbConect.GetAnsweredRating() && (l>0 && l%3 == 0))
					pupRating.show();

				ActualizarProgressBar();
			}else
			{
				AlertDialog a = new AlertDialog.Builder(this).create();				
				a.setButton(this.getResources().getString(R.string.btnSDUnmount), new DialogInterface.OnClickListener() {					
					public void onClick(DialogInterface dialog, int which) {
						finish();
						android.os.Process.killProcess( android.os.Process.myPid() ); 					
					}
				});

				a.setMessage(this.getResources().getString(R.string.msjSDUnmount));
				a.show();
			}
		}catch (Exception e) 
		{
			lblErrores.setText("Error al cargar: "+e.getMessage());	
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onDestroy() {
		adView.destroy();
		super.onDestroy();
	}

	public boolean onOptionsItemSelected(MenuItem item) 
	{ 
		if(item.getItemId() == R.id.itmAgregarCat)
			pupCate.Show(true);
		else if(item.getItemId() == R.id.itmEliminarCat)
			pupCate.Show(false);
		else if(item.getItemId() == R.id.itmMensual)
			pupConfirma.show("ReestMes",null);
		else if (item.getItemId() == R.id.itmAnual)
			pupConfirma.show("ReestAnio", null);
		else if (item.getItemId() == R.id.itmTodos)
			pupConfirma.show("ReestTodos",null);
		else if(item.getItemId() == R.id.itmCorregir)
			pupModif.show(true);
		else if(item.getItemId() == R.id.itmRatings)
			pupRating.show();
		else if(item.getItemId() == R.id.itmConfig)
			pupConfig.show();

		return true;
	}

	public void SetControls()
	{
		btnResta = (Button) findViewById(R.id.btnResta);
		txtIngresos = (EditText) findViewById(R.id.txtIngresos);
		txtEgresos =(EditText) findViewById(R.id.txtEgresos);
		txtResta = (EditText) findViewById(R.id.txtResta);			
		lblPorcentaje = (TextView) findViewById(R.id.lblPorcentaje);			 
		lblErrores = (TextView) findViewById(R.id.lblErrores);		
		chbMedio = (CheckBox) findViewById(R.id.chbMedio);

		skTotal = (ProgressBar) findViewById(R.id.skTotal);
		spnCategorias = (Spinner) findViewById(R.id.spnCategorias);	

		btnIr = (ImageButton) findViewById(R.id.btnIr);
		btnVolver =  (ImageButton) findViewById(R.id.btnVolver);
		flpView = (ViewFlipper) findViewById(R.id.flpView);  
		tblIngresos = (TableLayout) findViewById(R.id.tblIngresos);

		btnMil = (Button)  findViewById(R.id.btn1000);
		btnQuinientos = (Button)  findViewById(R.id.btn500);
		btnCien = (Button)  findViewById(R.id.btn100);
		btnCincuenta = (Button)  findViewById(R.id.btn50);
		btnDiez = (Button)  findViewById(R.id.btn10);
		btnCinco = (Button)  findViewById(R.id.btn5);
		btnUno = (Button)  findViewById(R.id.btn1);
		btnAtras = (ImageButton)  findViewById(R.id.btnAtras);
		btnDeshacer = (ImageButton) findViewById(R.id.btnDeshacer);
		btnAyuda = (ImageButton) findViewById(R.id.btnAyuda);
		ValoresAnteriores = new ArrayList<Integer>();	

		btnCategorias = (ImageButton) findViewById(R.id.btnCategorias);						
	}

	public void SetControlValues()
	{		
		CargarSpinnerCategorias();
		SetListenerBotones(new Button[]{btnMil,btnQuinientos,btnCien,btnCincuenta,btnDiez,btnCinco,btnUno});
	}

	public void SetListenerBotones(Button[] btns)
	{
		for (Button bt : btns) {
			bt.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					ClickSumar(((Button)v).getText().toString());
				}
			});
		}

		btnDeshacer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {				
				pupConfirma.show("Main", null);
			}
		});

		btnResta.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {				
				if(!txtResta.getText().toString().equals("")){
					if(!chbMedio.isChecked()){
						GuardarMovimiento(Integer.parseInt(txtResta.getText().toString()),"Eg",Utils.GetFecha(),Utils.medioEft,((ItemCategoria) spnCategorias.getSelectedItem()).Codigo,1);						
					}else{
						int id = GuardarMovimiento(Integer.parseInt(txtResta.getText().toString()),"Eg",Utils.GetFecha(),Utils.medioCred,((ItemCategoria) spnCategorias.getSelectedItem()).Codigo,1);
						pupTarjeta.show(id);						
					}
					ActualizarProgressBar();
					txtResta.setText("");
					ValoresAnteriores = new ArrayList<Integer>();
				}
				chbMedio.setChecked(false);
			}
		});

		btnCategorias.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				try{									
					pupPorce.CargarPantallaPorcentajes();
					pupPorce.show();
				}catch(Exception e)
				{
					lblErrores.setText(e.getMessage());					
				}
			}
		});

		btnAtras.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(ValoresAnteriores.size()>0 && !ValoresAnteriores.get(ValoresAnteriores.size()-1).equals(0))
				{
					txtResta.setText(String.valueOf(ValoresAnteriores.get(ValoresAnteriores.size()-1)));
					ValoresAnteriores.remove(ValoresAnteriores.size()-1);
				}
				else
					txtResta.setText("");
			}
		});

		btnIr.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {				
				flpView.setInAnimation(inFromRightAnimation());
				flpView.setOutAnimation(outToLeftAnimation());
				flpView.showNext();				
				PagosGrilla = new ArrayList<ItemIngresos>();
				SetBotonesGrilla();
				Spinner spnCate = (Spinner) findViewById(R.id.spnCate);				

				ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(v.getContext(),android.R.layout.simple_spinner_item, DbConect.GetFechasSpinner());
				spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);		
				spnCate.setAdapter(spinnerAdapter);	

				spnCate.setOnItemSelectedListener(new OnItemSelectedListener() {

					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if(arg0.getSelectedItem().toString().equals(arg1.getResources().getString(R.string.spnItemCate))){				
							CargarGrilla(DbConect.GetIngresos());
						}
						else if(arg0.getSelectedItem().toString().length()==4){
							CargarGrilla(DbConect.GetIngresosAnio(arg0.getSelectedItem().toString()));
						}
						else{
							CargarGrilla(DbConect.GetIngresosMes(arg0.getSelectedItem().toString().replace(" - ", "")));
						}
					}

					public void onNothingSelected(AdapterView<?> arg0) {}

				});

				CargarGrilla(DbConect.GetIngresos());
			}
		});

		btnVolver.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {				
				flpView.setInAnimation(inFromLeftAnimation());
				flpView.setOutAnimation(outToRightAnimation());
				flpView.showNext();
				tblIngresos = (TableLayout) findViewById(R.id.tblIngresos);			
			}
		});

		btnAyuda.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) 
			{
				pupAyuda.show();
			}
		});
	}

	public void CargarSpinnerCategorias()
	{	
		ArrayAdapter<ItemCategoria> spinnerAdapter = new ArrayAdapter<ItemCategoria>(this,android.R.layout.simple_spinner_item, DbConect.GetCategorias("spnCategorias",true,false));
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);		
		spnCategorias.setAdapter(spinnerAdapter);	
	}

	public void ClickSumar(String txt)
	{		

		int total=0;
		if(txtResta.getText().toString().length()>0)
			total = Integer.parseInt(txtResta.getText().toString());
		ValoresAnteriores.add(total);
		total += Integer.parseInt(txt.substring(1));
		txtResta.setText(String.valueOf( total));
	}

	public int GuardarMovimiento(int txt, String tipo, String fecha, String medio, int categoria, int estado) {
		try {
			return DbConect.InsertMovimiento(txt, tipo, fecha,medio,categoria,estado);
		}catch (Exception e) {
			lblErrores.setText("Error al cargar: "+e.getMessage());
			return -1;
		}
	}

	public void ActualizarProgressBar()
	{			
		int ingreso = DbConect.GetTotalMovimientosMes("In", Utils.GetMesAnio());
		int egreso = DbConect.GetTotalMovimientosMes("Eg",Utils.GetMesAnio());

		txtIngresos.setText("$"+String.valueOf(ingreso));
		txtEgresos.setText("$"+String.valueOf(egreso));

		double porcentaje = (ingreso>0)?100-((egreso * 100)/ingreso):0;
		long pesos = ingreso-egreso;			

		lblPorcentaje.setText("$"+String.valueOf(pesos) +" ~ "+String.valueOf(porcentaje) + "%");

		skTotal.setMax(100);
		skTotal.setProgress((int) porcentaje);

		skTotal.setEnabled(false);
	}

	public boolean DBOpen(){
		Resources r = getResources();
		try 
		{
			DbConect= new DbAdapter(this,r);
			if(DbConect.CheckearSD()){
				DbConect.createDataBase();	
				DbConect.openDataBase();			
				DbConect.ActualizarBaseDatos();
				DbConect.CopiarAyuda();				
			}else
				return false;
		} catch (IOException e) {
			lblErrores.setText(e.getMessage());
			return false;
		}
		return true;
	}

	public void CargarGrilla(final List<ItemIngresos> list)
	{		
		final Button btnPagar = (Button) findViewById(R.id.btnPagar);	

		tblIngresos.removeAllViews();
		if(list.size()>0){
			for (ItemIngresos itm : list) {
				final ItemIngresos it = itm;
				int clr = Utils.GetColor(itm.Categoria==null); 
				TableRow tr = new TableRow(this);
				TableRow.LayoutParams prm  =new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);				
				tr.setLayoutParams(prm);				
				tr.setGravity(Gravity.CENTER_VERTICAL);

				TextView txt  = new TextView(this);
				txt.setTextAppearance(this, android.R.style.TextAppearance_Small);
				txt.setTextSize(Utils.ConvertDpToPx(8));
				prm  =new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
				txt.setLayoutParams(prm);
				txt.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.marco1));
				txt.setTextColor(clr);
				txt.setText((itm.Categoria!=null)?itm.Categoria.Descripcion:this.getResources().getString(R.string.pupIngresos));
				tr.addView(txt);

				TextView txt1  = new TextView(this);
				txt1.setTextAppearance(this, android.R.style.TextAppearance_Small);
				txt1.setTextSize(Utils.ConvertDpToPx(8));
				prm  =new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
				txt1.setTextColor(clr);
				txt1.setLayoutParams(prm);
				txt1.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.marco1));
				String fecha = (Locale.getDefault().getLanguage().equals(Utils.codEspanol))?itm.Fecha:Utils.ChangeDateToEn(itm.Fecha); 
				txt1.setText(fecha);
				tr.addView(txt1);

				TextView txt2  = new TextView(this);
				txt2.setTextAppearance(this, android.R.style.TextAppearance_Small);
				txt2.setTextSize(Utils.ConvertDpToPx(8));
				prm  =new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
				txt2.setTextColor(clr);
				txt2.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.marco1));
				txt2.setLayoutParams(prm);
				txt2.setText(String.valueOf("$"+itm.Valor));
				tr.addView(txt2);

				TextView txt3  = new TextView(this);
				txt3.setTextAppearance(this, android.R.style.TextAppearance_Small);
				txt3.setTextSize(Utils.ConvertDpToPx(8));
				prm  =new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
				txt3.setTextColor(clr);
				txt3.setLayoutParams(prm);
				txt3.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.marco1));
				txt3.setText(itm.GetCuotasPagos());
				tr.addView(txt3);

				TextView txt4  = new TextView(this);
				txt4.setTextAppearance(this, android.R.style.TextAppearance_Small);
				txt4.setTextSize(Utils.ConvertDpToPx(8));
				prm  =new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
				txt4.setTextColor(clr);
				txt4.setLayoutParams(prm);
				txt4.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.marco1));
				txt4.setText(itm.GetMedio());
				tr.addView(txt4);

				ImageButton im= new ImageButton(this);
				im.setImageResource(R.drawable.edita);
				im.setPadding(5, 0, 5, 0);
				im.setBackgroundColor(Color.parseColor("#00000000"));
				im.setScaleType(ScaleType.CENTER_CROP);
				im.setOnClickListener(new View.OnClickListener() {					
					public void onClick(View v) {
						pupModif.show(it);
					}
				});
				tr.addView(im);

				RelativeLayout rlt = new RelativeLayout(this); 
				prm  =new TableRow.LayoutParams(40,21);
				prm.setMargins(Utils.ConvertDpToPx(2.0), 0, 0, 0);
				rlt.setLayoutParams(prm);
				rlt.setGravity(Gravity.CENTER);
				if(itm.Medio.equals(Utils.medioCred) && itm.Cuotas>itm.Pagos){
					CheckBox  chb = new CheckBox(this);
					chb.setGravity(Gravity.CENTER);
					chb.setButtonDrawable(R.drawable.chb);
					chb.setOnClickListener(new View.OnClickListener() {					
						public void onClick(View v) 
						{						
							if(((CheckBox)v).isChecked()){
								IdsGrilla.add(it.Id);
								if(it.Medio.equals(Utils.medioCred))
									PagosGrilla.add(it);
							}
							else{
								IdsGrilla.remove(IdsGrilla.indexOf(it.Id));
								if(it.Medio.equals(Utils.medioCred))
								{
									for (int i = 0; i < PagosGrilla.size(); i++) {
										if(PagosGrilla.get(i).Id.equals(it.Id)){
											PagosGrilla.remove(it);
											break;
										}
									}		
								}						
							}

							btnPagar.setEnabled(false);
							if(IdsGrilla.size()>0 && it.Medio.equals(Utils.medioCred))
								btnPagar.setEnabled(true);
						}
					});
					rlt.addView(chb);
				}
				tr.addView(rlt);			

				tblIngresos.addView(tr);
			}			
		}
	}

	private void SetBotonesGrilla()
	{
		final Button btnPagar = (Button) findViewById(R.id.btnPagar);		

		btnPagar.setOnClickListener(new View.OnClickListener() {					
			public void onClick(View v) {
				DbConect.PagarMovimientosTarjeta(PagosGrilla);
				ActualizarProgressBar();
				CargarGrilla(DbConect.GetIngresos());
				btnPagar.setEnabled(false);
				PagosGrilla = new ArrayList<ItemIngresos>();
			}
		});
	}

	private Animation inFromRightAnimation() {
		Animation inFromRight = new TranslateAnimation(         
				Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,              
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f               
				);
		inFromRight.setDuration(500);           
		inFromRight.setInterpolator(new AccelerateInterpolator());

		return inFromRight;
	}

	private Animation outToLeftAnimation() {
		Animation outtoLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
				);
		outtoLeft.setDuration(500);
		outtoLeft.setInterpolator(new AccelerateInterpolator());

		return outtoLeft;
	}

	private Animation inFromLeftAnimation() {               
		Animation inFromLeft = new TranslateAnimation(          
				Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,              
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f               
				);

		inFromLeft.setDuration(500);            
		inFromLeft.setInterpolator(new AccelerateInterpolator());

		return inFromLeft;              
	}

	private Animation outToRightAnimation() {               
		Animation outtoRight = new TranslateAnimation(          
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,              
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f               
				);

		outtoRight.setDuration(500);            
		outtoRight.setInterpolator(new AccelerateInterpolator());

		return outtoRight;              
	}
}